package bysj.filter;

import test.Helper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@WebFilter(filterName = "Filter_jwt 1",urlPatterns = {"/*"})
public class Filter_jwt implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("Filter 1 - encoding begins");
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //获得path
        String path = request.getRequestURI();
        //如果没有字串“/login”，则考虑设置字符编码
        if(!path.contains("/login")){
            String token = request.getHeader("token");
            //验证token是否存在
            if(token != null) {
                //验证token是否正确
                Collection<String> verify = Helper.verify(token,response);
                System.out.println(verify);
                if(verify.size()!=0){
                    //遍历verify，判断是否有相应权限
                    for(String s:verify){
                        System.out.println(s);
                        //如果是空
                        if(s==null){
                            break;
                        }else if(s.equals("http://localhost:8080"+path)){
                            chain.doFilter(req,resp);
                            return;
                        }
                    }
                }
            }
        }else if(path.contains("/login")){
            //执行其他过滤器，如过滤器已经执行完毕，则执行原请求
            chain.doFilter(req,resp);
        }
        System.out.println("Filter 1 - encoding ends");
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
